<script setup>
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import {deletePersonalAward, getPersonalAward, getPersonalAwardsByIds} from '@/api/Manage/personalAward.js';
import PersonalAwardExport from "@/components/ExportDialog/personalAwardExport.vue";
import SoftWareExport from "@/components/ExportDialog/softWareExport.vue";
import { emit } from '@/utils/eventBus';
import {mergeImagesToPdf} from "@/api/Manage/File.js";
const router = useRouter();
const dateRange = ref(null);

const awardsMessage = ref({
  list: [],
  total: 0
});
const exportData = ref([]);
const showExportDialog = ref(false);
const PersonalAwardTable=ref(null);
const params = reactive({
  isAsc: true,
  pageNo: 1,
  pageSize: 10,
  sortBy: 'id',
  startDate: "",
  endDate: "",
  total: 0,
  awardLevel:null
});

// 新增：用于存储所有选中项的ID
const selectedIds = ref([]);
// 新增：当前页面的所有ID
const currentPageIds = computed(() => {
  return awardsMessage.value.list ? awardsMessage.value.list.map(item => item.id) : [];
});
// 新增：选中项数量
const selectedCount = computed(() => selectedIds.value.length);
// 新增：标记是否需要重新设置选择状态
const needResetSelection = ref(false);
// 新增：标记是否选择了全部数据
const isAllSelected = ref(false);

const awardOptions = [
  { value: '一等奖', label: '一等奖' },
  { value: '二等奖', label: '二等奖' },
  { value: '三等奖', label: '三等奖' },
  { value: '金', label: '金' },
  { value: '银', label: '银' },
  { value: '铜', label: '铜' },
  { value: '冠', label: '冠' },
  { value: '亚', label: '亚' },
  { value: '季', label: '季' },
  { value: '特等奖', label: '特等奖' },
  { value: '优秀奖', label: '优秀奖' },
  { value: '入围奖', label: '入围奖' },
  { value: '优秀指导教师奖', label: '优秀指导教师奖' },
  { value: '优秀组织奖', label: '优秀组织奖' },
  { value: '不计等次', label: '不计等次' },
  { value: '其他', label: '其他' }
];

onMounted(() => {
  queryAwardsMessage();
});

// 新增：监听数据变化，设置选中状态
watch(() => awardsMessage.value.list, (newVal) => {
  if (newVal && newVal.length > 0) {
    needResetSelection.value = true;
    // 使用 nextTick 确保在 DOM 更新后再设置选择状态
    nextTick(() => {
      if (needResetSelection.value) {
        setTableSelection();
        needResetSelection.value = false;
      }
    });
  }
}, { deep: true });

const upload = () => {
  router.push("/main/add/Personal/Award");
};

const queryAwardsMessage = async () => {
  try {
    const res = await getPersonalAward(params);
    if (res.code === 1) {
      console.log("res.data", res.data);
      awardsMessage.value = res.data;
      params.total = res.data.total;

      console.log("Initial AwardsMessage:", awardsMessage.value);

      if (Array.isArray(awardsMessage.value.list)) {
        awardsMessage.value.list.forEach(award => {
          if (award.awardTime !== undefined) {
            console.log("Formatting awardTime:", award.awardTime);
            award.awardTime = formatDate(award.awardTime);
          } else {
            console.warn("awardTime is undefined for award:", award);
          }
        });
      } else {
        console.warn("AwardsMessage.list is not an array:", awardsMessage.value.list);
      }

      console.log("Formatted AwardsMessage:", awardsMessage.value);
    } else {
      console.error("Request failed with code:", res.code);
    }
  } catch (error) {
    console.error("Request error:", error);
  }
};

// 新增：设置表格选中状态
const setTableSelection = () => {
  // 确保表格组件已经挂载
  if (!PersonalAwardTable.value) return;

  // 先清除所有选择
  PersonalAwardTable.value.clearSelection();

  // 如果选择了全部数据，则选中当前页所有行
  if (isAllSelected.value) {
    setTimeout(() => {
      awardsMessage.value.list.forEach(row => {
        PersonalAwardTable.value.toggleRowSelection(row, true);
      });
    }, 50);
    return;
  }

  // 延迟一下再设置选中状态，确保清除操作已完成
  setTimeout(() => {
    // 遍历当前页的数据，设置选中状态
    awardsMessage.value.list.forEach(row => {
      if (selectedIds.value.includes(row.id)) {
        PersonalAwardTable.value.toggleRowSelection(row, true);
      }
    });
  }, 50);
};

// 新增：全选当前页
const selectAllCurrentPage = (val) => {
  if (val) {
    // 全选当前页
    currentPageIds.value.forEach(id => {
      if (!selectedIds.value.includes(id)) {
        selectedIds.value.push(id);
      }
    });
  } else {
    // 取消全选当前页
    selectedIds.value = selectedIds.value.filter(id => !currentPageIds.value.includes(id));
  }
};

// 新增：选择全部数据
const selectAllData = async () => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
        `确定要选择全部${params.total}条数据吗？`,
        '选择全部数据',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }
    );

    // 标记为已选择全部
    isAllSelected.value = true;

    // 选中当前页所有行
    if (PersonalAwardTable.value) {
      awardsMessage.value.list.forEach(row => {
        PersonalAwardTable.value.toggleRowSelection(row, true);
      });
    }

    ElMessage.success(`已选择全部${params.total}条数据`);
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('选择全部数据失败');
      console.error('选择全部数据失败:', error);
    } else {
      console.log('用户取消选择全部数据');
    }
  }
};

// 新增：取消选择全部
const cancelSelectAll = () => {
  isAllSelected.value = false;
  selectedIds.value = [];

  if (PersonalAwardTable.value) {
    PersonalAwardTable.value.clearSelection();
  }

  ElMessage.info('已取消选择全部数据');
};

function formatDate(timestamp) {
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

const download = async (row) => {
  // 显示加载状态，因为合并PDF可能需要一定时间
  const loading = ElLoading.service({
    lock: true,
    text: '正在生成PDF文件，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {

    const response = await mergeImagesToPdf(row.pdfPath);

    // 处理返回的文件流
    const blob = new Blob([response.data], { type: 'application/pdf' });
    const url = window.URL.createObjectURL(blob);

    // 创建下载链接
    const a = document.createElement('a');
    a.href = url;
    // 使用项目名称作为文件名
    a.download = `${row.title || '合并文件'}.pdf`;
    document.body.appendChild(a);
    a.click();

    // 清理资源
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);

    ElMessage.success('PDF生成并下载成功');
  } catch (error) {
    console.error('下载失败:', error);
    // 根据错误信息显示更具体的提示
    if (error.response && error.response.status === 404) {
      ElMessage.error('文件不存在');
    } else if (error.response && error.response.status === 400) {
      ElMessage.error('无效的文件路径');
    } else {
      ElMessage.error('生成PDF失败，请稍后重试');
    }
  } finally {
    // 无论成功失败都关闭加载状态
    loading.close();
  }
};

// 新增：预览PDF
const previewPdf = (row) => {
  router.push({
    path: '/preview',
    query: {
      pdfUrl: encodeURIComponent(row.pdfPath),
      title: encodeURIComponent(row.title || '个人获奖PDF'),
      type: 'personalAward', // 添加类型参数
      id: row.id, // 添加ID参数
    }
  });
};

const edit = (row) => {
  router.push({ path: '/main/edit/Personal/Award', query: { id: row.id } });
  console.log('编辑:', row);
};

const remove = async (row) => {
  try {
    await ElMessageBox.confirm('您确定删除吗？', '确认删除', { type: "warning" });
    const res = await deletePersonalAward(row.id);
    if (res.code === 1) {
      ElMessage.success('删除成功');

      // 新增：从选中项中移除已删除的ID
      selectedIds.value = selectedIds.value.filter(id => id !== row.id);

      await queryAwardsMessage();
      // 触发刷新事件
      emit('refresh-counts');
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error("Delete error:", error);
    }
  }
};

// 新增：处理行点击事件
const handleRowClick = (row, column, event) => {
  // 检查是否点击的是操作列（避免与操作按钮冲突）
  if (column.label === '操作') {
    return;
  }

  // 如果有PDF路径，则触发预览
  if (row.pdfPath) {
    previewPdf(row);
  }
};

// 新增：处理表格选择变化
const handleSelectionChange = (selection) => {
  // 如果已经选择了全部数据，不需要更新selectedIds
  if (isAllSelected.value) return;

  // 获取当前选中行的ID
  const currentSelectedIds = selection.map(item => item.id);

  // 从已选ID中移除当前页面上未被选中的ID
  const unselectedIds = currentPageIds.value.filter(id => !currentSelectedIds.includes(id));
  selectedIds.value = selectedIds.value.filter(id => !unselectedIds.includes(id));

  // 添加新选中的ID
  currentSelectedIds.forEach(id => {
    if (!selectedIds.value.includes(id)) {
      selectedIds.value.push(id);
    }
  });

  console.log('当前选中的ID:', selectedIds.value);
};

const handleSizeChange = (pageSize) => {
  params.pageSize = pageSize;
  queryAwardsMessage();
};

const handleCurrentChange = (pageNum) => {
  params.pageNo = pageNum;
  queryAwardsMessage();
};

const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  // 为有PDF的行添加手型光标
  if (row.pdfPath && column.label !== '操作') {
    return {
      padding: '15px',
      cursor: 'pointer'
    };
  }
  return { padding: '15px' };
};

const tableRowClassName = ({ row, rowIndex }) => {
  return 'custom-row';
};

// 处理日期变化
const handleDateChange = (val) => {
  if (val) {
    params.startDate = val[0];
    params.endDate = val[1];
  } else {
    params.startDate = "";
    params.endDate = "";
  }
  params.pageNo = 1; // 重置页码

  // 新增：重置选择状态
  selectedIds.value = [];
  isAllSelected.value = false;

  queryAwardsMessage();
};

// 处理排名变化
const handleRankChange = (val) => {
  params.pageNo = 1; // 重置页码

  // 新增：重置选择状态
  selectedIds.value = [];
  isAllSelected.value = false;

  queryAwardsMessage();
};

// 新增：分批获取数据并导出
const batchExportData = async () => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在导出数据，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {
    // 准备查询参数
    const queryParams = {
      isAsc: params.isAsc,
      sortBy: params.sortBy,
      startDate: params.startDate,
      endDate: params.endDate,
      awardLevel: params.awardLevel,
      pageSize: 50, // 每批获取50条数据
      pageNo: 1
    };

    // 获取第一批数据，同时获取总数
    const firstBatchRes = await getPersonalAward(queryParams);
    if (firstBatchRes.code !== 1 || !firstBatchRes.data) {
      throw new Error('获取数据失败');
    }

    // 计算总页数
    const total = firstBatchRes.data.total;
    const totalPages = Math.ceil(total / queryParams.pageSize);

    // 收集所有数据
    let allData = [...firstBatchRes.data.list];

    // 获取剩余批次的数据
    for (let page = 2; page <= totalPages; page++) {
      queryParams.pageNo = page;
      const res = await getPersonalAward(queryParams);
      if (res.code === 1 && res.data && Array.isArray(res.data.list)) {
        allData = [...allData, ...res.data.list];
      } else {
        console.warn(`获取第${page}页数据失败`);
      }
    }

    // 更新导出数据
    exportData.value = allData;

    // 关闭加载提示
    loadingInstance.close();

    // 显示导出对话框
    showExportDialog.value = true;

    return allData;
  } catch (error) {
    loadingInstance.close();
    ElMessage.error('导出失败: ' + error.message);
    console.error('导出失败:', error);
    throw error;
  }
};

// 修改：导出函数
const exportSelectedMessage = async () => {
  if (!isAllSelected.value && selectedIds.value.length === 0) {
    ElMessage.warning('请选择要导出的个人获奖');
    return;
  }

  try {
    if (isAllSelected.value) {
      // 使用分批获取数据的方式导出全部数据
      await batchExportData();
    } else {
      // 导出选中的数据
      const res = await getPersonalAwardsByIds(selectedIds.value);
      console.log('获取到的导出数据:', res);
      if (res.code === 1 && res.data) {
        // 更新 exportData
        exportData.value = Array.isArray(res.data) ? res.data : [res.data];
        // 打开导出对话框
        showExportDialog.value = true;
      } else {
        ElMessage.error('获取数据失败');
      }
    }
  } catch (error) {
    console.error("导出数据失败:", error);
    ElMessage.error('导出失败');
  }
};
</script>
<template>
  <div>
    <!-- 头部 -->
    <div class="header">
      <div class="title">
        <span class="title-text">个人获奖</span>
        <span class="title-count">{{ awardsMessage.total }}</span>
      </div>

      <div class="actions">
        <el-button type="primary" @click="upload">上 传</el-button>
        <el-button type="primary" @click="exportSelectedMessage">导 出</el-button>
      </div>
    </div>

    <!-- 筛选条件区域 -->
    <div class="filter-container">
      <div class="filter-item">
        <span class="filter-label">获奖时间：</span>
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
            class="custom-date-picker"
        />
      </div>

      <div class="filter-item">
        <span class="filter-label">获奖名次：</span>
        <el-select
            v-model="params.awardLevel"
            placeholder="请选择排名"
            clearable
            @change="handleRankChange"
            class="custom-select"
        >
          <el-option
              v-for="option in awardOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
          />
        </el-select>
      </div>
    </div>

    <!-- 新增：选择全部按钮区域 -->
    <div class="select-all-container">
      <div v-if="!isAllSelected">
        <el-button type="primary" plain size="small" @click="selectAllData">
          选择全部数据
        </el-button>
        <span class="selection-info" v-if="selectedCount > 0">
          已选择 {{ selectedCount }} 条数据
        </span>
      </div>
      <div v-else>
        <el-button type="warning" plain size="small" @click="cancelSelectAll">
          取消选择全部
        </el-button>
        <span class="selection-info">已选择全部 {{ params.total }} 条数据</span>
      </div>
    </div>

    <div class="table-container">
      <el-table
          ref="PersonalAwardTable"
          :data="awardsMessage.list"
          style="width: 100%"
          :cell-style="cellStyle"
          :row-class-name="tableRowClassName"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @select-all="selectAllCurrentPage">
        <el-table-column
            type="selection"
            width="85"
            align="center"
        >
        </el-table-column>
        <el-table-column
            prop="title"
            label="奖项名称"
            width="240"
            align="center">
        </el-table-column>
        <el-table-column
            prop="level"
            width="110"
            label="获奖级别"
            align="center">
        </el-table-column>
        <el-table-column
            prop="awardLevel"
            width="100"
            label="获奖等级"
            align="center">
        </el-table-column>

        <el-table-column
            prop="awardTime"
            label="获奖时间"
            width="140"
            align="center">
          <template #default="scope">
            {{ formatDate(scope.row.awardTime) }}
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="230"
            align="center">
          <template #default="scope">
            <el-button size="small" @click="download(scope.row)" :disabled="!scope.row.pdfPath">下载</el-button>
            <el-button size="small" type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="remove(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pageNo"
        :page-sizes="[10, 30, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next"
        :total="params.total"
        class="pagination"
    />

    <personal-award-export :personal="exportData" v-model="showExportDialog" />
  </div>
</template>

<style scoped>
.header {
  height: 60px; /* 替换 8.1vh */
  width: 880px; /* 替换 55vw */
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px; /* 添加内边距 */
}

.title {
  display: flex;
  align-items: center;
}

.title-text {
  font-weight: bold;
  font-size: 18px; /* 替换 1.1rem */
  margin-left: 20px; /* 替换 2vw */
}

.title-count {
  font-weight: bold;
  font-size: 18px; /* 替换 1.1rem */
  margin-left: 10px; /* 替换 0.5vw */
}

.actions {
  margin-right: 30px; /* 替换 3vw */
  display: flex;
  gap: 10px; /* 替换 1vw */
}

.custom-date-picker {
  width: 320px !important;
}

.custom-select {
  width: 160px;
}

.filter-container {
  display: flex;
  align-items: center;
  gap: 20px;
  border-radius: 8px;
  margin: 10px 30px;
}

.filter-item {
  display: flex;
  align-items: center;
}

.filter-label {
  margin-right: 10px;
  font-size: 14px;
  color: #606266;
}

/* 新增：选择全部按钮区域样式 */
.select-all-container {
  margin: 10px 30px;
  display: flex;
  align-items: center;
}

.selection-info {
  margin-left: 10px;
  color: #606266;
  font-size: 14px;
}

.table-container {
  width: 880px; /* 替换 55vw */
  overflow-y: auto;
  margin: 0 auto; /* 居中 */
}

.pagination {
  margin-left: 10px;
  padding-bottom: 10px;
  margin-top: 20px; /* 替换 2vh */
}

.el-button--large {
  padding: 12px 20px;
  font-size: 16px;
  min-width: 120px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>
